const { SysModel, ChapCodeModel, ImgModel } = require('../model')
const { getRandomNum, Result } = require('../utils')
const bcrypt = require('bcryptjs')
const { generateToken } = require('../utils/jwt')
/**
 * 登录接口
 * @param {*} data
 * @returns
 */
async function getLoginByAccount(data) {
    // 查新该账号是否注册
    let user = await SysModel.findOne({ phone: data.phone })
    // const username = "测试用户"
    if (!user) {
        // 没有就注册
        const user = new SysModel({
            name: 'gester',
            age: 18,
            sex: 1,
            phone: data.phone,
            nickName: data.phone,
            password: '123456',
            avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            createTime: new Date(),
            updateTime: new Date(),
            addr: ''
        })
        await user.save()
    }
    // 查询验证码
    let chapCode = await ChapCodeModel.findOne({ phone: data.phone, code: data.code })
    if (!chapCode) {
        return {
            code: 0,
            msg: '验证码错误'
        }
    }

    const token = generateToken({ phone: data.phone }) // 生成 JWT 令牌

    // 返回token
    return Result.success(token, '登录成功')
}

// 用户注册
const register = async ctx => {
    const { username, password } = ctx.request.body
    const hashedPassword = await bcrypt.hash(password, 10) // 加密密码
    users.push({ username, password: hashedPassword })
    ctx.body = { message: 'User registered successfully' }
}

async function getByUserInfoByPhone(phone) {
    return SysModel.findOne({ phone })
}

async function create(userData) {
    return SysModel.create(userData)
}

async function handleChapCode(data) {
    // 清空所有的验证码
    await ChapCodeModel.deleteMany({})
    let result = null
    let code = new ChapCodeModel({
        phone: data.tel,
        code: getRandomNum()
    })

    await code.save()

    return Result.success(code.code, '发送成功')
}

async function handleUploadFile(ctx) {
    // console.log('ctx.request.file', ctx.request.file)
    // console.log('ctx.file', ctx.file)
    // console.log('ctx.request.body', ctx.request.body)
    const { phone } = ctx.state.user
    const url = 'http://localhost:3000/images/' + ctx.file.filename
    if (!ctx.file) {
        ctx.status = 400
        ctx.body = { error: 'No file uploaded' } // 如果没有文件上传
        return
    }

    const img = new ImgModel({
        phone,
        url
    })
    await img.save()
    return Result.success(url, '上传成功')
}

const handleUpdateUserInfo = async ctx => {
    const { phone } = ctx.state.user
    const { body } = ctx.request
    console.log('🚀 ~ handleUpdateUserInfo ~ body:', body)
    try {
        const result = await SysModel.updateOne({ phone }, { $set: { nickname: body.nickname, avatar: body.avatar } })
        console.log('🚀 ~ handleUpdateUserInfo ~ result:', result)
        if (result.modifiedCount === 1) {
            return Result.success(null, '更新成功')
        } else {
            return Result.error(500, null, '更新失败')
        }
    } catch (error) {}
}

module.exports = {
    getLoginByAccount,
    getByUserInfoByPhone,
    create,
    handleChapCode,
    handleUploadFile,
    handleUpdateUserInfo
}
